package com.sskj.mine.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.arouter.utils.TextUtils;
import com.bulong.rudeness.RudenessScreenHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.box.decoration.SectionDividerItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.MineFragmentPresenter;
import com.sskj.mine.util.HideUtil;
import com.sskj.mine.util.TipMineUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.MINE_FRAGMENT_MAIN)//我的主页
public class MineFragment extends BaseFragment<MineFragmentPresenter> {
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.iv_mine_head)
    ImageView ivMineHead;
    @BindView(R2.id.tv_mine_exit)
    TextView tvMineExit;
    @BindView(R2.id.tv_mine_user_name)
    TextView tvMineUserName;
    @BindView(R2.id.tv_mine_zhzc_num)
    TextView tvMineZhzc;
    @BindView(R2.id.tv_mine_zhzc_num_rmb)
    TextView tvMineZhzcRmb;
    @BindView(R2.id.recycler_mine)
    RecyclerView recyclerMine;
    private UserData userData;
    private MaterialDialog tip;

    private BaseAdapter<MineData> mineAdapter;
    private MaterialDialog loginTip;

    @Override
    protected int getLayoutId() {
        return R.layout.mine_fragment_main0;
    }

    @Override
    protected MineFragmentPresenter getPresenter() {
        return new MineFragmentPresenter();
    }

    @Override
    public void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            updateUI();
        });
        initRecy();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && userViewModel != null) {
            userViewModel.update();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden && userViewModel != null) {
            userViewModel.update();
        }
        super.onHiddenChanged(hidden);
    }

    private void initRecy() {
        recyclerMine.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerMine.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setLastDraw(false)
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 40))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 40))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.mine_525869))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
        recyclerMine.addItemDecoration(new SectionDividerItemDecoration(getActivity(), 3)
                .setSectionHeight((int) RudenessScreenHelper.pt2px(App.INSTANCE, 10))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.mine_0e1624)));
        mineAdapter = new BaseAdapter<MineData>(R.layout.mine_recy_item_mine, new ArrayList<>(), recyclerMine) {
            @Override
            public void bind(ViewHolder holder, MineData item) {
                holder.setText(R.id.tv_item_mine, item.getName())
                        .setImageResource(R.id.iv_item_mine, item.getImg())
                        .setText(R.id.tv_item_mine_version, APKVersionCodeUtils.getVerName(getActivity()));
                if (holder.getAdapterPosition() == 8) {
                    holder.setVisible(R.id.iv_item_mine_right, false)
                            .setVisible(R.id.tv_item_mine_version, true);
                }
            }
        };
        initRecyData();
        mineAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position < 7 && position != 4 && userData == null) {
                if (loginTip == null) {
                    loginTip = TipMineUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.mineMineFragment1), App.INSTANCE.getString(R.string.mineMineFragment2), () -> {
                        ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                    });
                }
                loginTip.show();
                return;
            }
            switch (position) {
                case 0://个人中心
                    ARouter.getInstance().build(RConfig.MINE_PERSON_CENTER).navigation();
                    break;
                case 1://安全中心
                    ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
                    break;
                case 2://资产管理
                    ARouter.getInstance().build(RConfig.MINE_ASSETS).navigation();
                    break;
                case 3://提币地址
                    ARouter.getInstance().build(RConfig.MINE_WALLET_ADDRESS_MANAGER).navigation();
                    break;
                case 4://平台公告
                    ARouter.getInstance().build(RConfig.GONGGAO_ACTIVITY_MAIN).navigation();
                    break;
                case 5://我的邀请
                    ARouter.getInstance().build(RConfig.MINE_WYTG).navigation();
                    break;
                case 6://邀请明细
                    ARouter.getInstance().build(RConfig.MINE_MY_TEAM).navigation();
                    break;
                case 7://关于我们
                    ARouter.getInstance().build(RConfig.MINE_ABOUT_US).navigation();
                    break;
                case 8:
                    RxBus.getDefault().send(RxBusCode.CHECK_VERSION);
                    break;
                default:
                    break;
            }
        });
    }

    private void initRecyData() {
        List<MineData> mineDatas = new ArrayList<>();
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_grzx", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.minePersonCenterActivity0)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_aqzx", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineSecurityCenterActivity0)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_zcgl", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineAssetsActivity0)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_tbdz", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineWalletAddressManagerActivity0)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_ptgg", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineMineFragment7)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_wdtg", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineMineFragment10)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_tgmx", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineMineFragment11)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_anout_us", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineMineFragment8)));
        mineDatas.add(new MineData(App.INSTANCE.getResources().getIdentifier("mine_dqbb", "mipmap", App.INSTANCE.getPackageName()), App.INSTANCE.getString(R.string.mineMineFragment12)));
        mineAdapter.addData(mineDatas);
    }

    /**
     * 根据用户信息更新页面
     */
    private void updateUI() {
        if (userData != null) {
            if (TextUtils.isEmpty(userData.getMobile())) {
                tvMineUserName.setText(userData.getMail());
            } else {
                tvMineUserName.setText(HideUtil.getPhoneHide(userData.getMobile()));
            }
            tvMineZhzc.setText(NumberUtil.keep4(userData.getUsdt()));
            tvMineZhzcRmb.setText(String.format(App.INSTANCE.getString(R.string.mine_dialog_tip50), NumberUtil.keep4(userData.getRmb())));
            ClickUtil.click(tvMineUserName, () -> {
            });
            tvMineExit.setVisibility(View.VISIBLE);

            ClickUtil.click(tvMineExit, () -> {
                if (tip == null) {
                    tip = TipMineUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.mineMineFragment0), () -> {
                        LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
                        tvMineZhzc.setText(NumberUtil.keep4("0"));
                        tvMineZhzcRmb.setText(String.format(App.INSTANCE.getString(R.string.mine_dialog_tip50), NumberUtil.keep4("0")));
                        logoutProvider.logout();
                    });
                }
                tip.show();
            });
        } else {
            tvMineUserName.setText(App.INSTANCE.getString(R.string.mine_fragment_main90));
            ClickUtil.click(tvMineUserName, () -> {
                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
            });
            tvMineExit.setVisibility(View.GONE);
            tvMineZhzc.setText(NumberUtil.keep4("0"));
            tvMineZhzcRmb.setText(String.format(App.INSTANCE.getString(R.string.mine_dialog_tip50), NumberUtil.keep4("0")));
        }
    }

    private class MineData {
        private int img;
        private String name;

        public MineData(int img, String name) {
            this.img = img;
            this.name = name;
        }

        public int getImg() {
            return img;
        }

        public void setImg(int img) {
            this.img = img;
        }

        public String getName() {
            return name == null ? "" : name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }


    //    @Inject
//    UserViewModel userViewModel;
//    @BindView(R2.id.tvAccount)
//    TextView tvAccount;
//    @BindView(R2.id.tvMoney)
//    TextView tvMoney;
//    @BindView(R2.id.recyclerView)
//    RecyclerView recyclerView;
//    @BindView(R2.id.llLogin)
//    LinearLayout llLogin;
//
//    @BindView(R2.id.ivChangeLan)
//    ImageView ivChangeLan;
//    @BindView(R2.id.btExit)
//    Button btExit;
//    private UserData userData;
//    private List<MainItemBean> items;
//    private MaterialDialog tip;
//    private MaterialDialog loginTip;
//    private int curLanguagePos = 0;
//
//    @Override
//    protected int getLayoutId() {
//        return R.layout.mine_fragment_main;
//    }
//
//
//
//    @Override
//    public MineFragmentPresenter getPresenter() {
//        return new MineFragmentPresenter();
//    }
//
//    @Override
//    public void initView() {
//        DaggerUserDataComponent.create().inject(this);
//        userViewModel.getUsers().observe(this, users -> {
//            if (users != null && users.size() > 0) {
//                userData = users.get(0);
//            } else {
//                userData = null;
//            }
//            updateUI();
//        });
//        initItem();
//        initRecy();
//        if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(LanguageUtil.getAppLocale(getActivity()).getLanguage())) {
//            curLanguagePos = 0;
//            ImageUtil.setImage(R.mipmap.mine_language_cn, ivChangeLan);
//        } else {
//            curLanguagePos = 1;
//            ImageUtil.setImage(R.mipmap.mine_language_en, ivChangeLan);
//        }
//        ClickUtil.click(ivChangeLan, () -> {
//            if (curLanguagePos == 0) {
//                curLanguagePos = 1;
//            } else {
//                curLanguagePos = 0;
//            }
//            switchLanguage();
//        });
//
//        userViewModel.update();
//    }
//
//    private void initRecy() {
//        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
//                .setFirstDraw(false)
//                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
//                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
//        recyclerView.addItemDecoration(new SectionDividerItemDecoration(getActivity(), 3)
//                .setSectionHeight((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20)));
//            SlimAdapter slimAdapter = SlimAdapter.create().register(R.layout.mine_recy_item_main, new SlimInjector<MainItemBean>() {
//                    @Override
//                    public void onInject(MainItemBean data, IViewInjector injector, List payloads) {
//                        injector
//                                .text(R.id.tvTitle, data.getTitle())
//                                .image(R.id.ivTitle, data.getIcon());
//                    }
//                });
//                slimAdapter.attachTo(recyclerView).updateData(items);
//        ItemClickSupport.addTo(recyclerView)
//                .setOnItemClickListener((recyclerView, position, v) -> {
//                    if (position < 4 && userData == null) {
//                        if (loginTip == null) {
//                            loginTip = TipMineUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.mineMineFragment1), App.INSTANCE.getString(R.string.mineMineFragment2), () -> {
//                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
//                            });
//                        }
//                        loginTip.show();
//                        return;
//                    }
//                    switch (position) {
//                        case 0:
//                            ARouter.getInstance().build(RConfig.MINE_PERSON_CENTER).navigation();
//                            break;
//                        case 1:
//                            ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
//                            break;
//                        case 2:
//                            ARouter.getInstance().build(RConfig.MINE_ASSETS).navigation();
//                            break;
//                        case 3:
//                            ARouter.getInstance().build(RConfig.MINE_WALLET_ADDRESS_MANAGER).navigation();
//                            break;
//                        case 4:
//                            ARouter.getInstance().build(RConfig.GONGGAO_ACTIVITY_MAIN).navigation();
//                            break;
//                        case 5:
//                            ARouter.getInstance().build(RConfig.MINE_ABOUT_US).navigation();
//                            break;
//                    }
//                });
//    }
//
//    private void initItem() {
//        items = new ArrayList<>();
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_person, App.INSTANCE.getString(R.string.mineMineFragment3)));
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_security, App.INSTANCE.getString(R.string.mineMineFragment4)));
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_assets, App.INSTANCE.getString(R.string.mineMineFragment5)));
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_address, App.INSTANCE.getString(R.string.mineMineFragment6)));
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_ptgg, App.INSTANCE.getString(R.string.mineMineFragment7)));
//        items.add(new MainItemBean(R.mipmap.mine_icon_main_about_us, App.INSTANCE.getString(R.string.mineMineFragment8)));
//    }
//
//    /**
//     * 根据用户信息更新页面
//     */
//    private void updateUI() {
//        if (userData != null) {
//            llLogin.setVisibility(View.VISIBLE);
//            if (TextUtils.isEmpty(userData.getTel())) {
//                tvAccount.setText(userData.getEmail());
//            } else {
//                tvAccount.setText(HideUtil.getPhoneHide(userData.getTel()));
//            }
//            tvMoney.setText(userData.getUsableFund());
//            ClickUtil.click(tvAccount, () -> {
//            });
//            btExit.setVisibility(View.VISIBLE);
//
//            ClickUtil.click(btExit, () -> {
//                if (tip == null) {
//                    tip = TipMineUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.mineMineFragment0), () -> {
//                        LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
//                        logoutProvider.logout();
//                    });
//                }
//                tip.show();
//            });
//
//        } else {
//            llLogin.setVisibility(View.VISIBLE);
//            tvAccount.setText(App.INSTANCE.getString(R.string.mineMineFragment9));
//            ClickUtil.click(tvAccount, () -> {
//                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
//            });
//            tvMoney.setText("0.00");
//            btExit.setVisibility(View.GONE);
//        }
//    }
//
//    public void switchLanguage() {
//        if (curLanguagePos == 1) {
//            setLocale(Locale.ENGLISH);
//        } else {
//            setLocale(Locale.SIMPLIFIED_CHINESE);
//        }
//    }
//
//    public void setLocale(Locale myLocale) {
//        Resources res = getResources();
//        DisplayMetrics dm = res.getDisplayMetrics();
//        Configuration conf = res.getConfiguration();
//        conf.locale = myLocale;
//        res.updateConfiguration(conf, dm);
//        LanguageUtil.saveLanguageSetting(getActivity(), myLocale);
//        refreshSelf();
//    }
//
//
//    public void refreshSelf() {
////        RxBus.getDefault().send(RxBusCode.CHANGE_LANGUAGE);
//        getActivity().finish();
//        ARouter.getInstance().build(RConfig.APP_MAIN).withInt(Constans.POS, 3).navigation();
//    }
}
